package milu.models;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Text;

import java.util.*;
import milu.*;

@PersistenceCapable
public class RecipeComment {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Persistent
    private Key recipeKey; // recipe this comment belongs to

    @Persistent
    private Key userKey; // user that created this comment

    @Persistent
    private Date created; // date the comment was created

    @Persistent
    private Text comment; // comment itself

    public RecipeComment(Key recipeKey, Key userKey, Text comment) {
        this.created = new Date();
        this.recipeKey = recipeKey;
        this.userKey = userKey;
        this.comment = comment;
    }
    public MyUser getAuthor() {
        PersistenceManager pm = Datastore.getPersistenceManager();
        MyUser myUser = pm.getObjectById(MyUser.class, this.userKey);
        return myUser;
    }
    public Date getCreated() {
        return created;
    }
    public Text getComment() {
        return comment;
    }

    public static List<RecipeComment> getCommentsForRecipe(Key recipeKey) {
        PersistenceManager pm = Datastore.getPersistenceManager();

        Query query = pm.newQuery(RecipeComment.class, "this.recipeKey == recipeKey");
        query.setOrdering("created asc");
        query.declareImports("import com.google.appengine.api.datastore.Key");
        query.declareParameters("Key recipeKey");
        List<RecipeComment> comments = (List<RecipeComment>)query.execute(recipeKey);

        return comments;
    }
}
